import { ref, watch } from 'vue'

export type ThemeMode = 'light' | 'dark' | 'auto'
export type ColorScheme = 'default' | 'blue' | 'green' | 'purple' | 'orange'

export interface ThemeConfig {
  mode: ThemeMode
  colorScheme: ColorScheme
  fontSize: number
  fontFamily: string
  lineHeight: number
  editorTheme: string
  accentColor: string
  borderRadius: number
  animations: boolean
  transparency: boolean
}

export interface CustomTheme {
  id: string
  name: string
  description: string
  config: Partial<ThemeConfig>
  colors: {
    primary: string
    secondary: string
    accent: string
    background: string
    surface: string
    text: string
    textSecondary: string
    border: string
  }
}

class ThemeService {
  private currentTheme = ref<ThemeConfig>({
    mode: 'light',
    colorScheme: 'default',
    fontSize: 14,
    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
    lineHeight: 1.6,
    editorTheme: 'default',
    accentColor: '#3b82f6',
    borderRadius: 8,
    animations: true,
    transparency: true
  })

  private customThemes = ref<CustomTheme[]>([])
  private systemPrefersDark = ref(false)

  constructor() {
    this.initializeTheme()
    this.setupSystemThemeDetection()
    this.loadCustomThemes()
  }

  // 初始化主题
  private initializeTheme() {
    const savedTheme = localStorage.getItem('editor-theme')
    if (savedTheme) {
      try {
        const parsed = JSON.parse(savedTheme)
        this.currentTheme.value = { ...this.currentTheme.value, ...parsed }
      } catch (error) {
        console.warn('Failed to parse saved theme:', error)
      }
    }

    this.applyTheme()

    watch(this.currentTheme, (newTheme) => {
      this.applyTheme()
      this.saveTheme()
    }, { deep: true })
  }

  // 设置系统主题检测
  private setupSystemThemeDetection() {
    if (typeof window !== 'undefined' && window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      this.systemPrefersDark.value = mediaQuery.matches

      mediaQuery.addEventListener('change', (e) => {
        this.systemPrefersDark.value = e.matches
        if (this.currentTheme.value.mode === 'auto') {
          this.applyTheme()
        }
      })
    }
  }

  // 加载自定义主题
  private loadCustomThemes() {
    const savedCustomThemes = localStorage.getItem('editor-custom-themes')
    if (savedCustomThemes) {
      try {
        this.customThemes.value = JSON.parse(savedCustomThemes)
      } catch (error) {
        console.warn('Failed to parse custom themes:', error)
      }
    }

    this.addPresetThemes()
  }

  // 添加预设主题
  private addPresetThemes() {
    const presetThemes: CustomTheme[] = [
      {
        id: 'github',
        name: 'GitHub',
        description: '仿 GitHub 风格的清爽主题',
        config: {
          colorScheme: 'default',
          fontSize: 14,
          lineHeight: 1.5,
          borderRadius: 6
        },
        colors: {
          primary: '#0969da',
          secondary: '#656d76',
          accent: '#0969da',
          background: '#ffffff',
          surface: '#f6f8fa',
          text: '#24292f',
          textSecondary: '#656d76',
          border: '#d0d7de'
        }
      },
      {
        id: 'vscode-dark',
        name: 'VS Code Dark',
        description: '仿 VS Code 深色主题',
        config: {
          colorScheme: 'blue',
          fontSize: 14,
          lineHeight: 1.4,
          borderRadius: 4,
          editorTheme: 'dark'
        },
        colors: {
          primary: '#007acc',
          secondary: '#cccccc',
          accent: '#007acc',
          background: '#1e1e1e',
          surface: '#252526',
          text: '#cccccc',
          textSecondary: '#969696',
          border: '#3c3c3c'
        }
      }
    ]

    presetThemes.forEach(preset => {
      if (!this.customThemes.value.find(theme => theme.id === preset.id)) {
        this.customThemes.value.push(preset)
      }
    })

    this.saveCustomThemes()
  }

  // 应用主题
  private applyTheme() {
    const theme = this.currentTheme.value
    const isDark = this.getEffectiveThemeMode() === 'dark'

    const root = document.documentElement
    root.classList.toggle('dark', isDark)

    const colorSchemes = this.getColorSchemes()
    const currentScheme = colorSchemes[theme.colorScheme] || colorSchemes.default
    const colors = isDark ? currentScheme.dark : currentScheme.light

    Object.entries(colors).forEach(([key, value]) => {
      root.style.setProperty(`--color-${key}`, value)
    })

    root.style.setProperty('--font-size-base', `${theme.fontSize}px`)
    root.style.setProperty('--font-family-base', theme.fontFamily)
    root.style.setProperty('--line-height-base', theme.lineHeight.toString())
    root.style.setProperty('--border-radius-base', `${theme.borderRadius}px`)
    root.style.setProperty('--accent-color', theme.accentColor)
    root.style.setProperty('--transition-duration', theme.animations ? '0.2s' : '0s')
    root.style.setProperty('--backdrop-opacity', theme.transparency ? '0.8' : '1')
  }

  // 获取有效的主题模式
  private getEffectiveThemeMode(): 'light' | 'dark' {
    if (this.currentTheme.value.mode === 'auto') {
      return this.systemPrefersDark.value ? 'dark' : 'light'
    }
    return this.currentTheme.value.mode
  }

  // 获取颜色方案
  private getColorSchemes() {
    return {
      default: {
        light: {
          primary: '#3b82f6',
          secondary: '#64748b',
          accent: '#3b82f6',
          background: '#ffffff',
          surface: '#f8fafc',
          text: '#0f172a',
          'text-secondary': '#64748b',
          border: '#e2e8f0',
          success: '#10b981',
          warning: '#f59e0b',
          error: '#ef4444',
          info: '#3b82f6'
        },
        dark: {
          primary: '#60a5fa',
          secondary: '#94a3b8',
          accent: '#60a5fa',
          background: '#0f172a',
          surface: '#1e293b',
          text: '#f1f5f9',
          'text-secondary': '#94a3b8',
          border: '#334155',
          success: '#34d399',
          warning: '#fbbf24',
          error: '#f87171',
          info: '#60a5fa'
        }
      },
      blue: {
        light: {
          primary: '#2563eb',
          secondary: '#64748b',
          accent: '#1d4ed8',
          background: '#ffffff',
          surface: '#f1f5f9',
          text: '#1e293b',
          'text-secondary': '#64748b',
          border: '#cbd5e1',
          success: '#059669',
          warning: '#d97706',
          error: '#dc2626',
          info: '#2563eb'
        },
        dark: {
          primary: '#3b82f6',
          secondary: '#94a3b8',
          accent: '#2563eb',
          background: '#0c1426',
          surface: '#1e293b',
          text: '#f1f5f9',
          'text-secondary': '#94a3b8',
          border: '#334155',
          success: '#10b981',
          warning: '#f59e0b',
          error: '#ef4444',
          info: '#3b82f6'
        }
      }
    }
  }

  // 保存主题
  private saveTheme() {
    localStorage.setItem('editor-theme', JSON.stringify(this.currentTheme.value))
  }

  // 保存自定义主题
  private saveCustomThemes() {
    localStorage.setItem('editor-custom-themes', JSON.stringify(this.customThemes.value))
  }

  // 公共方法
  getCurrentTheme(): ThemeConfig {
    return this.currentTheme.value
  }

  setTheme(config: Partial<ThemeConfig>) {
    this.currentTheme.value = { ...this.currentTheme.value, ...config }
  }

  setThemeMode(mode: ThemeMode) {
    this.currentTheme.value.mode = mode
  }

  toggleTheme() {
    const currentMode = this.getEffectiveThemeMode()
    this.setThemeMode(currentMode === 'light' ? 'dark' : 'light')
  }

  getCustomThemes(): CustomTheme[] {
    return this.customThemes.value
  }

  addCustomTheme(theme: CustomTheme) {
    this.customThemes.value.push(theme)
    this.saveCustomThemes()
  }

  removeCustomTheme(id: string) {
    const index = this.customThemes.value.findIndex(theme => theme.id === id)
    if (index > -1) {
      this.customThemes.value.splice(index, 1)
      this.saveCustomThemes()
    }
  }

  applyCustomTheme(id: string) {
    const theme = this.customThemes.value.find(t => t.id === id)
    if (theme) {
      this.setTheme(theme.config)
    }
  }

  exportTheme(): string {
    return JSON.stringify(this.currentTheme.value, null, 2)
  }

  importTheme(themeJson: string): boolean {
    try {
      const theme = JSON.parse(themeJson)
      this.setTheme(theme)
      return true
    } catch (error) {
      console.error('Failed to import theme:', error)
      return false
    }
  }

  resetTheme() {
    this.currentTheme.value = {
      mode: 'light',
      colorScheme: 'default',
      fontSize: 14,
      fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
      lineHeight: 1.6,
      editorTheme: 'default',
      accentColor: '#3b82f6',
      borderRadius: 8,
      animations: true,
      transparency: true
    }
  }
}

export const themeService = new ThemeService()